export const FETCH_TIMER_REQUEST = "FETCH_TIMER_REQUEST";
function fetchTimerRequest (){
    return {type:FETCH_TIMER_REQUEST}
}


export const FETCH_TIMER_SUCCESS = "FETCH_TIMER_SUCCESS";
function fetchTimerSuccess (timers){
    return {type:FETCH_TIMER_SUCCESS,timers}
}

export function fetchTimer(){
    return function (dispatch){
        dispatch(fetchTimerRequest())
        apiClient.loadTimer().then((timer)=>{
            dispatch(fetchTimerSuccess(timer))
        })
    }
}


export const SAVE_TIMER_REQUEST = "SAVE_TIMER_REQUEST";
function saveTimerRequest (){
    return {type:SAVE_TIMER_REQUEST}
}


export const SAVE_TIMER_SUCCESS = "SAVE_TIMER_SUCCESS";
function saveTimerSuccess (timer){
    return {type:SAVE_TIMER_SUCCESS,timer}
}

export const SAVE_TIMER_FAIl = "SAVE_TIMER_FAIl";
function saveTimerFail (error){
    return {type:SAVE_TIMER_FAIl,error}
}

export function saveTimer(timer){
    return function (dispatch){
        dispatch(saveTimerRequest())
        apiClient.saveTimer(timer).then((timer)=>{
            dispatch(saveTimerSuccess(timer))
        }).catch((err)=>{
            dispatch(saveTimerFail(err))
        })
    }
}

const apiClient = {
    count:1,
    loadTimer:function (){
        return {
            then:function (cb){
                setTimeout(()=>{
                    cb(JSON.parse(localStorage.timer||'{}'))
                },1000)
            }
        }
    },
    saveTimer: function (timer){
        const success =!!(this.count++%2)
        return new Promise(function (resolve,reject) {
            setTimeout(()=>{
                localStorage.timer = JSON.stringify(timer);
                resolve({success})
            },1000);
        })
    }

}
